package me.chan.practice;

import me.chan.std.StdOut;

import java.util.Arrays;

/**
 * Created by JanGin on 2017/9/20.
 */
public class Domain implements Comparable<Domain> {

    private final String[] domain;
    private int length;

    public Domain(String domain) {
        this.domain = domain.split("\\.");
        this.length = this.domain.length;
    }

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder(domain[domain.length - 1]).append(".");
       for (int i=domain.length - 2; i > 0; i--) {
           str.append(domain[i]).append(".");
       }
        str.append(domain[0]);
        return str.toString();
    }

    @Override
    public int compareTo(Domain that) {
        int min = Math.min(this.length, that.length);
        for (int i = 0; i < min; i++ ) {
            String s1 = this.domain[this.length - i - 1];
            String s2 = that.domain[that.length - i - 1];
            int c = s1.compareTo(s2);
            return c > 0 ? 1:-1;
        }
        return this.length - that.length;
    }

    public static void main(String[] args) {

        //String[] names = StdIn.readAllStrings();
        String[] names = {"www.baidu.com",
                         "www.sina.com.cn",
                        "www.wikipedia.org",
                        "www.google.com.hk",
                        "www.amazon.jp"};
        Domain[] domains = new Domain[names.length];
        for (int i = 0; i < domains.length; i++) {
            domains[i] = new Domain(names[i]);
        }
        // sort
        Arrays.sort(domains);

        // print results
        for (int i = 0; i < domains.length; i++) {
            StdOut.println(domains[i]);
        }
        /**********************************/
        /**      cn.com.sina.www         **/
        /**      com.baidu.www           **/
        /**      hk.com.google.www       **/
        /**      jp.amazon.www           **/
        /**      org.wikipedia.www       **/
        /**                              **/
        /**********************************/

    }
}
